package com.sg.util.XMLTools;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;

import com.sg.util.XMLTools.entity.XMLNode;

public class XMLWriter {

	/**
	 * 根据xml节点生成xml文档
	 * @param node 节点对象
	 * @param os 输出流
	 * @throws IOException io异常
	 */
	public static void writeXML(XMLNode node, OutputStream os) throws IOException{
		Document document = DocumentHelper.createDocument();
		Element rootElement = document.addElement(node.getNodeTag());
		generatElement(rootElement, node);
		
		OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
		
		 OutputFormat of = new OutputFormat();  
	     of.setEncoding("utf-8");  
	     of.setIndent(true);  
	     of.setIndent("\t");  
	     of.setNewLineAfterDeclaration(false);
	     of.setNewlines(true);
	     of.setTrimText(true);
	     
	     org.dom4j.io.XMLWriter writer = new org.dom4j.io.XMLWriter(osw, of);  
	     writer.write(document);  
	     writer.close();  
	}
	
	/**
	 * 生成元素
	 * @param element 创建元素对象
	 * @param node 节点信息
	 */
	private static void generatElement(Element element, XMLNode node){
		element.setText(node.getNodeText());
		for (String key : node.getAttributes().keySet()) {
			element.addAttribute(key, node.getAttributes().get(key));
		}
		if (node.isParent()) {
			for (XMLNode childNode : node.getChilds()) {
				generatElement(element.addElement(childNode.getNodeTag()), childNode);
			}
		}
	} 
}
